//
//  ViewController.m
//  sqlite
//
//  Created by 谢泽锋 on  0 7/10/1 .
//  Copyright ©  017年 Xie泽锋. All rights reserved.
//

#import "ViewController.h"
#import <FMDB.h>
#import "DatabaseManagement.h"
#import "MessageModel.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    int page;
}
 @property(nonatomic,strong)FMDatabase *db;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UITextField *texts;
@property(nonatomic,strong)DatabaseManagement * dbManagment;
@property(nonatomic,strong)NSMutableArray * dataSource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 0 ;
    NSString * timeStr = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970] * 1000];

    long int w = [timeStr longLongValue];
 
    NSArray * getData =  [self.dbManagment queryData:w Page:page ConversationID:@"111"];
    [self.dataSource insertObjects:getData atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, getData.count)]];

//    [self.dataSource addObjectsFromArray: getData];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView reloadData];

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    MessageModel * model = self.dataSource[indexPath.row];
    cell.detailTextLabel.text = model.messageContent;
    return cell;
}
-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource=[[NSMutableArray alloc]init];
    }
    return _dataSource;
}
-(DatabaseManagement *)dbManagment
{
    if (!_dbManagment) {
        _dbManagment=[DatabaseManagement CreateDatabase:@"zefeng"];
    }
    return _dbManagment;
}
- (IBAction)chaRu:(id)sender {
    
    MessageModel * model = [[MessageModel alloc]init];
    model.name = @"zefneg";
    model.messageContent = _texts.text;
    model.messageType = MessageTypeText;
    model.time = [[NSDate date] timeIntervalSince1970] * 1000;
    model.chatType = ChatTypeSingleChat;
    model.sendObject = SenderObjectMe;
    model.UserAccount = @"111";
    model.ConversationID = @"111";
    [self.dataSource addObject:model];
    [self.dbManagment insertData:model];
}
- (IBAction)chakan:(id)sender {
    NSInteger time = [[NSDate date] timeIntervalSince1970] * 1000;
//    NSNumber *number = [NSNumber numberWithInteger:time];
 
    NSString * timeStr = [NSString stringWithFormat:@"%ld",(long)time];
   long int w = [timeStr longLongValue];
    page++;
    NSArray * getData =  [self.dbManagment queryData:w Page:page ConversationID:@"111"];

//    [self.dataSource addObjectsFromArray: [self.dbManagment queryData:w Page:page ConversationID:@"111"]];
    [self.dataSource insertObjects:getData atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, getData.count)]];

    [self.myTableView reloadData];
}
//    //1.获得数据库文件的路径
//           NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//           NSString *fileName=[doc stringByAppendingPathComponent:@"ent.sqlite"];
//    NSLog(@"%@",fileName);
//         // .获得数据库
//         FMDatabase *db=[FMDatabase databaseWithPath:fileName];
//
//          // .打开数据库
//           if ([db open]) {
//                 // .创表
//               //name 用户名
//               //type 消息类型（发送者）
//               //messageType 消息类型（语音 或者文字）
//               //MessageContent 消息内容
//               //time 发送时间
//               //chatType 聊天类型 （单聊，群聊）
////               BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, type integer  NOT NULL, messageType integer NOT NULL,    MessageContent text NOT NULL,  time integer NOT NULL, chatType integer NOT NULL);"];
//
////               BOOL resuls=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, type integer  NOT NULL, messageType integer NOT NULL,    MessageContent text NOT NULL,  time integer NOT NULL, chatType integer NOT NULL);"];
//
//              BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, chatType integer NOT NULL,time integer,messageType integer,messageContent text NOT NULL,sendObject integer NOT NULL);"];
//
//           if (result)
//           {
//               NSLog(@"创表成功");
//           }else{
//              NSLog(@"创表失败");
//
//           }
//     }
//           self.db=db;
////    for (int i = 0; i<10; i++) {
////                 NSString *name = [NSString stringWithFormat:@"jack-%d", arc4random_uniform(100)];
//                 // executeUpdate : 不确定的参数用?来占位
////        [self.db executeUpdate:@"INSERT INTO t_student (name, type，messageType，MessageContent，time，chatType) VALUES (?,?,?,?,?,?);", name,1,2,@"sadfsfsdfsdfa",3, 4];
//
////           [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", name, @(arc4random_uniform(40))];
//                //        [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);" withArgumentsInArray:@[name, @(arc4random_uniform(40))]];
//
//                 // executeUpdateWithFormat : 不确定的参数用%@、%d等来占位
//                //        [self.db executeUpdateWithFormat:@"INSERT INTO t_student (name, age) VALUES (%@, %d);", name, arc4random_uniform(40)];
////           }
//
//}
//- (IBAction)action:(id)sender {
//
//   NSString * query =  [NSString stringWithFormat:@"select * from t_student where time < '%d' order by id desc limit 100 offset 2 ", 200];
//    FMResultSet *rs = [self.db executeQuery:query];
//
//    NSLog(@"-------------%d",rs.columnCount);
//
//    while ([rs next]) {
//        NSLog(@"%@",[rs stringForColumn:@"time"]);
//        NSLog(@"name ==  %@",[rs stringForColumn:@"name"]);
//
//    }
//
//}
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    NSLog(@"------------------------------------");
//    for (int i=0; i<100; i++) {
//        NSString *name = [NSString stringWithFormat:@"jack-%d", arc4random_uniform(100000)];
//        NSLog(@"%@",name);
//        // executeUpdate : 不确定的参数用?来占位
//        [self.db executeUpdate:@"INSERT INTO t_student (name, chatType,time,messageType,messageContent,sendObject) VALUES (?, ?, ?, ?, ?, ?);", name, @(arc4random_uniform(40)),@(arc4random_uniform(1000)),@(arc4random_uniform(1000)),@"messageContent",@(0)];
//
//
//    }
//    NSLog(@"------------------------------------");
//}
- (IBAction)other:(id)sender {
    MessageModel * model = [[MessageModel alloc]init];
    model.name = @"zefneg";
    model.messageContent = _texts.text;
    model.messageType = MessageTypeText;
    model.time = [[NSDate date] timeIntervalSince1970] * 1000;
    model.chatType = ChatTypeSingleChat;
    model.sendObject = SenderObjectMe;
    model.UserAccount = @"111";
    model.ConversationID = @"111";
    [self.dataSource addObject:model];
    [self.myTableView reloadData];

    [self.dbManagment insertData:model];
}
- (IBAction)me:(id)sender {
    MessageModel * model = [[MessageModel alloc]init];
    model.name = @"zefneg";
    model.messageContent = _texts.text;
    model.messageType = MessageTypeText;
    model.time = [[NSDate date] timeIntervalSince1970] * 1000;
    model.chatType = ChatTypeSingleChat;
    model.sendObject = SenderObjectMe;
    model.UserAccount = @"222";
    model.ConversationID = @"111";
    [self.dataSource addObject:model];
    [self.myTableView reloadData];
    [self.dbManagment insertData:model];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
